/*
 * UserInterface.cpp
 *
 *  Created on: Jan 18, 2015
 *      Author: toti
 */

#include <UI/UserInterface.hpp>


UserInterface::UserInterface()
	: LocalClient(0){

	Config *config = Config::instance();


	unlink(config->getClientInputFile().c_str());
	if((mkfifo(config->getClientInputFile().c_str(), 0777)) == -1){
		fprintf(stderr, "FIFO fail\n");
	    exit(0);
	}

	ofs = new std::ofstream(Config::instance()->getClientOutputFile());

	inputFileDescriptor = open(Config::instance()->getClientInputFile().c_str(), O_RDWR | O_NONBLOCK);

}

void UserInterface::handleInputData(std::list<MessagePackage*> *messageList){

	char inputChar;
	std::string inputString;

	while(read(inputFileDescriptor,&inputChar,sizeof(char)) > 0){
		if(inputChar != '\n'){
			inputString.append(sizeof(char),inputChar);
		}else{
			ClientMessagePackage *clientMessagePackage = new ClientMessagePackage(this,inputString);
			clientMessagePackage->parseMessageString();

			messageList->push_back(clientMessagePackage);

			inputString.assign("");
		}
	}


}

void UserInterface::handleOutputData(MessagePackage *messagePackage){

	ClientMessagePackage *clientMessagePackage = (ClientMessagePackage*)messagePackage;
	//clientMessagePackage->generateMessageString();

	*ofs << clientMessagePackage->getText();
	*ofs << std::endl;
	ofs->flush();

}


MessagePackage *UserInterface::buildPackage(std::string& input){

	ClientMessagePackage *clientMessagePackage = new ClientMessagePackage(this, input);
	clientMessagePackage->parseMessageString();
	return clientMessagePackage;

}

int UserInterface::getInputFileDescriptor(){
	return inputFileDescriptor;
}
